<template>
  <div class="messages-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>消息中心</h1>
        <p>与客户沟通，及时回复提升服务质量</p>
      </div>
      <div class="header-actions">
        <div class="business-status">
          <span class="status-label">营业状态：</span>
          <el-tag :type="businessStatus.isOpen ? 'success' : 'danger'">
            {{ businessStatus.isOpen ? '营业中' : '已打烊' }}
          </el-tag>
          <el-button
            :type="businessStatus.isOpen ? 'danger' : 'success'"
            size="small"
            @click="toggleBusinessStatus"
            :loading="statusChanging"
            style="margin-left: 10px;"
          >
            {{ businessStatus.isOpen ? '停止营业' : '开始营业' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 营业时间提醒 -->
    <el-alert
      v-if="!businessStatus.isOpen"
      title="非营业时间提醒"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template #default>
        <p>当前处于非营业时间，消息回复不会影响店铺综合分数和流量。</p>
        <p>营业时间：{{ businessStatus.workingHours }}</p>
      </template>
    </el-alert>

    <!-- 消息统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card unread">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Message /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ messageStats.unread }}</div>
              <div class="stat-label">未读消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card system">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Bell /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ messageStats.system }}</div>
              <div class="stat-label">系统通知</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card order">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ messageStats.order }}</div>
              <div class="stat-label">订单消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card finance">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ messageStats.finance }}</div>
              <div class="stat-label">财务消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 消息列表 -->
    <el-card shadow="hover" class="messages-card">
      <template #header>
        <div class="card-header">
          <span>消息中心</span>
          <div class="header-actions">
            <el-select v-model="filterType" placeholder="消息类型" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all" />
              <el-option label="系统通知" value="system" />
              <el-option label="订单消息" value="order" />
              <el-option label="财务消息" value="finance" />
              <el-option label="评价消息" value="review" />
            </el-select>
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all" />
              <el-option label="未读" value="unread" />
              <el-option label="已读" value="read" />
            </el-select>
            <el-button-group>
              <el-button
                type="primary"
                @click="markAllAsRead"
                :disabled="unreadCount === 0"
              >
                <el-icon><Check /></el-icon>
                全部标记已读 ({{ unreadCount }})
              </el-button>
              <el-button
                type="danger"
                @click="deleteAllRead"
                :disabled="readCount === 0"
              >
                <el-icon><Delete /></el-icon>
                删除已读消息 ({{ readCount }})
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <div class="messages-list">
        <div v-for="message in filteredMessages" :key="message.id" class="message-item" :class="{ unread: !message.isRead }">
          <div class="message-icon" :class="message.type">
            <el-icon v-if="message.type === 'system'"><Bell /></el-icon>
            <el-icon v-else-if="message.type === 'order'"><Document /></el-icon>
            <el-icon v-else-if="message.type === 'finance'"><Money /></el-icon>
            <el-icon v-else-if="message.type === 'review'"><Star /></el-icon>
            <el-icon v-else><Message /></el-icon>
          </div>
          
          <div class="message-content" @click="handleMessageClick(message)">
            <div class="message-header">
              <div class="message-title">{{ message.title }}</div>
              <div class="message-meta">
                <el-tag :type="getTypeColor(message.type)" size="small">
                  {{ getTypeText(message.type) }}
                </el-tag>
                <span class="message-time">{{ message.createTime }}</span>
              </div>
            </div>
            <div class="message-text">{{ message.content }}</div>
          </div>
          
          <div class="message-actions">
            <el-button
              v-if="!message.isRead"
              type="primary"
              size="small"
              @click="markAsRead(message)"
            >
              标记已读
            </el-button>
            <el-button
              size="small"
              @click="deleteMessage(message)"
            >
              删除
            </el-button>
          </div>
        </div>
        
        <div v-if="filteredMessages.length === 0" class="empty-messages">
          <el-empty description="暂无消息" />
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalMessages"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息详情弹窗 -->
    <el-dialog
      v-model="messageDetailVisible"
      :title="currentMessage?.title"
      width="600px"
      @close="closeMessageDetail"
    >
      <div class="message-detail">
        <div class="detail-header">
          <el-tag :type="getTypeColor(currentMessage?.type)" size="small">
            {{ getTypeText(currentMessage?.type) }}
          </el-tag>
          <span class="detail-time">{{ currentMessage?.createTime }}</span>
        </div>
        <div class="detail-content">
          {{ currentMessage?.content }}
        </div>
        <div v-if="currentMessage?.extra" class="detail-extra">
          <h4>相关信息：</h4>
          <p v-for="(value, key) in currentMessage.extra" :key="key">
            <strong>{{ key }}：</strong>{{ value }}
          </p>
        </div>
      </div>
      <template #footer>
        <el-button @click="messageDetailVisible = false">关闭</el-button>
        <el-button
          v-if="!currentMessage?.isRead"
          type="primary"
          @click="markAsRead(currentMessage)"
        >
          标记已读
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  Document,
  Money,
  Star,
  Message,
  Check,
  Delete
} from '@element-plus/icons-vue'
import { useMessageStore } from '@/stores/message'

// 营业状态
const businessStatus = reactive({
  isOpen: true,
  workingHours: '08:00 - 22:00'
})

const statusChanging = ref(false)

// 响应式数据
const filterType = ref('all')
const filterStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const totalMessages = ref(0)
const messageDetailVisible = ref(false)
const currentMessage = ref(null)

// 消息store
const messageStore = useMessageStore()

// 消息统计
const messageStats = computed(() => messageStore.messageStats)

// 消息列表
const messages = computed(() => messageStore.messages)

// 计算属性
const filteredMessages = computed(() => {
  let filtered = messages.value

  if (filterType.value !== 'all') {
    filtered = filtered.filter(msg => msg.type === filterType.value)
  }

  if (filterStatus.value !== 'all') {
    const isRead = filterStatus.value === 'read'
    filtered = filtered.filter(msg => msg.isRead === isRead)
  }

  return filtered
})

const unreadCount = computed(() => {
  return messages.value.filter(msg => !msg.isRead).length
})

const readCount = computed(() => {
  return messages.value.filter(msg => msg.isRead).length
})

// 方法
const toggleBusinessStatus = async () => {
  try {
    const action = businessStatus.isOpen ? '停止营业' : '开始营业'
    await ElMessageBox.confirm(
      `确认${action}？${businessStatus.isOpen ? '停止后消息回复不影响评分' : '开始后需及时回复消息'}`,
      '营业状态',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    statusChanging.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))

    businessStatus.isOpen = !businessStatus.isOpen
    ElMessage.success(`已${action}`)
  } catch {
    ElMessage.info('已取消操作')
  } finally {
    statusChanging.value = false
  }
}

const getTypeColor = (type) => {
  const colorMap = {
    'system': 'info',
    'order': 'primary',
    'finance': 'success',
    'review': 'warning'
  }
  return colorMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    'system': '系统通知',
    'order': '订单消息',
    'finance': '财务消息',
    'review': '评价消息'
  }
  return textMap[type] || '其他'
}

// 点击消息
const handleMessageClick = (message) => {
  currentMessage.value = message
  messageDetailVisible.value = true
  
  // 如果是未读消息，自动标记为已读
  if (!message.isRead) {
    markAsRead(message)
  }
}

// 标记单个消息为已读
const markAsRead = async (message) => {
  if (!message.isRead) {
    const success = await messageStore.markAsRead(message.id)
    if (success) {
      ElMessage.success('已标记为已读')
    }
  }
}

// 标记全部为已读
const markAllAsRead = async () => {
  if (unreadCount.value === 0) {
    ElMessage.info('没有未读消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认将所有 ${unreadCount.value} 条未读消息标记为已读？`,
      '批量标记已读',
      {
        confirmButtonText: '确定标记',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const success = await messageStore.markAllAsRead()
    if (success) {
      ElMessage.success(`已将所有未读消息标记为已读`)
    }
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 删除所有已读消息
const deleteAllRead = async () => {
  if (readCount.value === 0) {
    ElMessage.info('没有已读消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认删除所有 ${readCount.value} 条已读消息？删除后无法恢复。`,
      '批量删除已读消息',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const success = await messageStore.deleteAllRead()
    if (success) {
      ElMessage.success(`已删除所有已读消息`)
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 删除消息
const deleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm('确认删除此消息？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const success = await messageStore.removeMessage(message.id)
    if (success) {
      ElMessage.success('消息已删除')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 关闭消息详情
const closeMessageDetail = () => {
  messageDetailVisible.value = false
  currentMessage.value = null
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 页面初始化
onMounted(async () => {
  console.log('📨 消息中心页面初始化')

  try {
    // 初始化消息store
    await messageStore.initStore()
    totalMessages.value = messages.value.length

    console.log('✅ 消息中心数据加载完成')
  } catch (error) {
    console.error('❌ 消息中心数据加载失败:', error)
    ElMessage.error('消息数据加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.messages-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.business-status {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 14px;
  color: #6b7280;
  margin-right: 8px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  overflow: hidden;
}

.stat-card.unread {
  border-left: 4px solid #f56c6c;
}

.stat-card.system {
  border-left: 4px solid #909399;
}

.stat-card.order {
  border-left: 4px solid #409eff;
}

.stat-card.finance {
  border-left: 4px solid #67c23a;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.unread .stat-icon {
  background: #f56c6c;
}

.system .stat-icon {
  background: #909399;
}

.order .stat-icon {
  background: #409eff;
}

.finance .stat-icon {
  background: #67c23a;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.messages-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.messages-list {
  min-height: 400px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f8fafc;
}

.message-item.unread {
  background-color: #fef7f0;
  border-left: 4px solid #f56c6c;
}

.message-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 16px;
  color: white;
}

.message-icon.system {
  background: #909399;
}

.message-icon.order {
  background: #409eff;
}

.message-icon.finance {
  background: #67c23a;
}

.message-icon.review {
  background: #e6a23c;
}

.message-content {
  flex: 1;
  cursor: pointer;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.message-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.message-time {
  font-size: 12px;
  color: #9ca3af;
}

.message-text {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.message-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 15px;
}

.empty-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.message-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
  }

  .detail-time {
    font-size: 12px;
    color: #9ca3af;
  }

  .detail-content {
    font-size: 14px;
    color: #374151;
    line-height: 1.6;
    margin-bottom: 20px;
  }

  .detail-extra {
    background: #f8fafc;
    border-radius: 6px;
    padding: 15px;

    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #1f2937;
    }

    p {
      margin: 5px 0;
      font-size: 13px;
      color: #6b7280;

      strong {
        color: #374151;
      }
    }
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}
</style>
